<template>
  <view class="pageBody" :class="{'flex': isLandscape}" id="signaturePage">
    <view class="bg-white mycanvasBody" :style="isLandscape ? 'width:80vw;height:40vw;' : 'width: 100vw; height: 50vw;'">
      <view class="tipsBox" :style="{ opacity: showTips ? 1 : 0 }">
        <u-icon name="edit-pen-fill" size="32" color="#999"></u-icon>
        <view class="tipsTitle">请在当前区域内签名</view>
      </view>
      <canvas
        class="mycanvas"
        style="width: 100vw; height: 50vw"
        canvas-id="mycanvas"
        @touchstart="touchstart"
        @touchmove="touchmove"
        @touchend="touchend"></canvas>
    </view>
    <view :class="isLandscape ? 'w-[16vw] ml-[2vw]' : 'grid grid-cols-2 gap-3 p-3'">
      <u-button text="重 写" @click="clear"></u-button>
      <u-button
        :class="{'mt-2': isLandscape}"
        type="primary"
        text="提 交"
        :throttleTime="500"
        @click="confirm"></u-button>
    </view>
  </view>
</template>

<script>
import { upFile } from '@/api/upFile'
import { useExpertStore } from '@/stores/expert'

export default {
  data() {
    return {
      showTips: true, // 是否显示画布提示

      ctx: '', //绘图图像
      points: [], //路径点集合
      signature: '',
      isLandscape: false, // 是否为竖屏
    }
  },
  mounted() {
    const that = this
    //创建绘图对象
    that.ctx = uni.createCanvasContext('mycanvas', this)
    //设置画笔样式
    that.ctx.lineWidth = 4
    that.ctx.lineCap = 'round'
    that.ctx.lineJoin = 'round'
    // 设置背景颜色
    const query = uni.createSelectorQuery().in(this)
    query
      .select('.mycanvas')
      .boundingClientRect((res) => {
        that.ctx.setFillStyle('#FFFFFF')
        that.ctx.fillRect(0, 0, Math.ceil(res.width), Math.ceil(res.height))
      })
      .exec()

    that.handleOrientationChange();
    window.addEventListener('orientationchange', that.handleOrientationChange);
    window.addEventListener('resize', that.handleOrientationChange);

    that.addTouchMoveListener(); // 阻止滚动行为
  },
  beforeUnmount() {
    this.removeTouchMoveListener(); // 移除阻止滚动事件
  },
  methods: {
    addTouchMoveListener() {
      document.addEventListener('touchmove', this.handleTouchMove, { passive: false });
    },
    removeTouchMoveListener() {
      document.removeEventListener('touchmove', this.handleTouchMove, { passive: false });
    },
    handleTouchMove(event) {
      event.preventDefault();
    },
    handleOrientationChange() {
      this.isLandscape = window.orientation === 90 || window.orientation === -90;
    },

    //触摸开始，获取到起点
    touchstart(e) {
      this.showTips = false
      let startX = e.changedTouches[0].x
      let startY = e.changedTouches[0].y
      let startPoint = {
        X: startX,
        Y: startY
      }
      this.points.push(startPoint)
      //每次触摸开始，开启新的路径
      this.ctx.beginPath()
    },
    //触摸移动，获取到路径点
    touchmove(e) {
      let moveX = e.changedTouches[0].x
      let moveY = e.changedTouches[0].y
      let movePoint = {
        X: moveX,
        Y: moveY
      }
      this.points.push(movePoint) //存点
      let len = this.points.length
      if (len >= 2) {
        this.draw() //绘制路径
      }
    },
    // 触摸结束，将未绘制的点清空防止对后续路径产生干扰
    touchend() {
      this.points = []
    },
    /* ***********************************************
			#   绘制笔迹
			#	1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
			#	2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
			#	3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
			************************************************ */
    draw() {
      let point1 = this.points[0]
      let point2 = this.points[1]
      this.points.shift()
      this.ctx.moveTo(point1.X, point1.Y)
      this.ctx.lineTo(point2.X, point2.Y)
      this.ctx.stroke()
      this.ctx.draw(true)
    },
    //清空画布
    clear() {
      const that = this
      uni.getSystemInfo({
        success: function (res) {
          let canvasw = res.windowWidth
          let canvash = res.windowHeight
          that.ctx.clearRect(0, 0, canvasw, canvash)
          that.ctx.draw(true)
          that.showTips = true
        }
      })
    },
    //完成绘画并保存到本地
    confirm() {
      const that = this
      const { setPrescriptionSign } = useExpertStore()
      if (that.showTips) {
        uni.showToast({
          title: '请书写签名后再提交哦!',
          icon: 'none'
        })
        return
      }
      uni.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function (res) {
          upFile({ url: res.tempFilePath }).then((_r) => {
            setPrescriptionSign(_r.url)
            uni.$u.route({
              type: 'navigateBack',
              delta: 1
            })
          })
        },
        fail: function (err) {
          console.log(err, 'canvas保存失败')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// #ifdef H5
body {
  height: 100%;
  width: 100%;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow-x: hidden;
  -webkit-overflow-scrolling: touch;
  touch-action: pan-y; // 只允许垂直滚动
}
// #endif
.pageBody {
  width: 100vw;
  height: 100vh;
  padding-top: 24rpx;
  background-color: #f5f5f5;
  // touch-action: none;
}
.mycanvasBody {
  border: dashed 1px #e2e2e2;
  border-radius: 8rpx;
  overflow: hidden;
  position: relative;
  .tipsBox {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .tipsTitle {
      font-size: 16px;
      color: #999999;
    }
  }
}
</style>
